<script setup lang="ts">
  import {
    ElDropdown,
    ElDropdownItem,
    ElDropdownMenu,
    ElTable,
    ElTableColumn,
    ElInput,
    ElIcon,
    ElSpace,
    ElDivider,
    ElMessageBox,
    TableInstance,
  } from 'element-plus'
  import Pagination from '@/components/Pagination/index.vue'
  import { Search, ArrowDown } from '@element-plus/icons-vue'
  import { h, ref } from 'vue'
  import {
    useDelSourceByIds,
    useDisableSourceByIds,
    useEnableSourceByIds,
    useGetOrderSourceList,
  } from '@/services/pages/order/useSoruce'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import CreateModal from './CreateModal.vue'

  const { del } = useDelSourceByIds()
  const { disable } = useDisableSourceByIds()
  const { enable } = useEnableSourceByIds()
  const { list, listTotal, getListParam, getListLoading, getList } = useGetOrderSourceList()

  defineOptions({
    name: 'OrderSourceList',
  })

  // 操作栏间隔符
  const spacer = h(ElDivider, { direction: 'vertical' })

  // 分页组件实例
  const paginationInstance = ref<InstanceType<typeof Pagination> | null>(null)

  // 来源选择列表
  const sourceSelectList = ref<Array<OrderSource>>([])

  // 批量操作方法映射
  const multipleOperateFnMap = {
    enable: enable,
    disable: disable,
    del: del,
  }

  // 创建弹窗显示状态
  const createModalVisible = ref(false)

  // 表单组件实例
  const tableInstance = ref<TableInstance | null>(null)

  // 正在编辑的来源id
  const editingSourceId = ref('')

  /**
   * 获取列表
   */
  const _getList = () => {
    if (paginationInstance.value) {
      getListParam.value.limit = paginationInstance.value.size
      getListParam.value.page = paginationInstance.value.current
      getList()
    }
  }

  /**
   * 列表选择事件
   * @param list - 选择的列表
   */
  const handleSelectionChange = (list: Array<OrderSource>) => {
    sourceSelectList.value = list
  }

  /**
   * 获取批量操作的消息弹出框的消息
   * @param type - 操作类型
   */
  const getMultipleOperateElMessageBoxMsg = (type: 'enable' | 'disable' | 'del') => {
    if (type === 'enable') {
      return '确定要启用选中的来源吗？'
    }

    if (type === 'disable') {
      return '确定要禁用选中的来源吗？'
    }

    return '确定要删除选中的来源吗？'
  }

  /**
   * 获取批量操作成功后的提醒
   * @param type - 操作类型
   */
  const getMultipleOperateSuccessTip = (type: 'enable' | 'disable' | 'del') => {
    if (type === 'enable') {
      return '启用成功'
    }

    if (type === 'disable') {
      return '禁用成功'
    }

    return '删除成功'
  }

  /**
   * 批量操作
   * @param type - 操作类型
   */
  const handleMultipleOperate = (type: 'enable' | 'disable' | 'del') => {
    if (type === 'del' && sourceSelectList.value.some((source) => source.systemd)) {
      HMessageBox.error('选中的来源中包含系统来源，不允许删除')
      return
    }

    ElMessageBox({
      title: '提示',
      message: getMultipleOperateElMessageBoxMsg(type),
      type: type === 'del' ? 'error' : 'warning',
      autofocus: false,
      showCancelButton: true,
      async beforeClose(action, instance, done) {
        const fn = multipleOperateFnMap[type]
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.cancelButtonLoading = true
          const res = await fn(sourceSelectList.value.map((item) => item.id))
          instance.confirmButtonLoading = false
          instance.cancelButtonLoading = false
          if (res.code === 20000) {
            _getList()
            done()
            HMessage.success(getMultipleOperateSuccessTip(type))
            return
          }
          if (res.code === 400305) {
            HMessageBox.error('选中的来源中包含系统来源，禁止删除')
            return
          }
          HMessageBox.error(res.message)
          return
        }

        done()
      },
    })
  }

  /**
   * 点击表格上的删除时触发
   * @param source - 来源
   */
  const handleDel = (source: OrderSource) => {
    if (tableInstance.value) {
      tableInstance.value.toggleRowSelection(source, true)
      ElMessageBox({
        title: '提示',
        type: 'error',
        autofocus: false,
        message: '确定删除该来源吗？',
        showCancelButton: true,
        async beforeClose(action, instance, done) {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.cancelButtonLoading = true
            const res = await del([source.id])
            instance.confirmButtonLoading = false
            instance.cancelButtonLoading = false
            if (res.code === 20000) {
              _getList()
              done()
              HMessage.success('删除成功')
              return
            }
            HMessageBox.error(res.message)
            return
          }
          done()
        },
      })
    }
  }

  /**
   * 详情事件
   * @param id - 来源id
   */
  const handleDetial = (id: string) => {
    editingSourceId.value = id
    createModalVisible.value = true
  }

  /**
   * 添加来源点击事件
   */
  const onCreateSource = () => {
    editingSourceId.value = ''
    createModalVisible.value = true
  }

  defineExpose({
    getList: _getList,
  })
</script>

<template>
  <div class="order-source-list">
    <div class="header">
      <div class="btn-group">
        <h-plain-button @click="onCreateSource">添加来源</h-plain-button>
        <el-dropdown trigger="click">
          <h-button :disabled="sourceSelectList.length === 0">
            批量操作
            <el-icon>
              <arrow-down></arrow-down>
            </el-icon>
          </h-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="handleMultipleOperate('enable')">批量启用</el-dropdown-item>
              <el-dropdown-item @click="handleMultipleOperate('disable')"
                >批量禁用</el-dropdown-item
              >
              <el-dropdown-item @click="handleMultipleOperate('del')">批量删除</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="search">
        <el-input
          v-model.trim="getListParam.name"
          placeholder="请输入关键字"
          clearable
          @keyup.enter="_getList"
          @clear="_getList"
        />
        <h-button type="primary" @click="_getList">
          <el-icon>
            <search />
          </el-icon>
          搜索
        </h-button>
      </div>
    </div>
    <div v-loading="getListLoading" class="body">
      <el-table
        ref="tableInstance"
        :border="true"
        height="100%"
        stripe
        :data="list"
        @selection-change="handleSelectionChange"
      >
        <!-- 选择 -->
        <el-table-column type="selection" width="50" fixed="left" :align="'center'">
        </el-table-column>

        <!-- 序号 -->
        <el-table-column
          type="index"
          width="50"
          :align="'center'"
          label="序号"
          fxied="left"
        ></el-table-column>

        <!-- 来源名称 -->
        <el-table-column label="来源名称" min-width="160" prop="name">
          <template #default="{ row }">
            <h-link @click="handleDetial(row.id)">{{ row.name }}</h-link>
          </template>
        </el-table-column>

        <!-- 是否为默认值 -->
        <el-table-column label="是否为默认值" width="100" prop="defaultSelect">
          <template #default="{ row }">{{ row.defaultSelect ? '是' : '否' }}</template>
        </el-table-column>

        <!-- 是否为系统来源 -->
        <el-table-column label="是否为系统来源" width="120" prop="systemd">
          <template #default="{ row }">{{ row.systemd ? '是' : '否' }}</template>
        </el-table-column>

        <!-- 创建时间 -->
        <el-table-column label="创建时间" prop="createTime" width="140"></el-table-column>

        <!-- 更新时间 -->
        <el-table-column label="更新时间" prop="updateTime" width="140"></el-table-column>

        <!-- 状态 -->
        <el-table-column label="状态" prop="status" width="70" :align="'center'">
          <template #default="{ row }">
            <div class="flex_justify_center">
              <h-status v-if="!row.status">启用</h-status>
              <h-status v-else type="info">禁用</h-status>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" prop="operate" width="90">
          <template #default="{ row }">
            <el-space :size="0" :spacer="spacer">
              <h-link @click="handleDetial(row.id)">编辑</h-link>
              <h-link v-if="!row.systemd" type="error" @click="handleDel(row)">删除</h-link>
            </el-space>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footer">
      <pagination
        ref="paginationInstance"
        :list_total="listTotal"
        @size-change="_getList"
        @current-change="_getList"
      />
    </div>

    <create-modal
      v-model:visible="createModalVisible"
      :source-id="editingSourceId"
      @update="_getList"
    />
  </div>
</template>

<style lang="scss" scoped>
  .order-source-list {
    height: 100%;
    display: flex;
    flex-direction: column;
    row-gap: 5px;

    .header {
      display: flex;
      justify-content: space-between;

      .btn-group {
        display: flex;
        column-gap: 5px;
      }

      .search {
        display: flex;
        column-gap: 5px;
      }
    }

    .footer {
      display: flex;
      justify-content: flex-end;
    }
  }
</style>
